﻿using Dtmcli;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MQCommon;
using MQCommon.SagaModel;
using MySqlConnector;
using SagaBusiness.Model;

namespace SagaBusiness.Controllers
{
    [Route("/api")]
    [ApiController]
    public class TccBusinessController : ControllerBase
    {
        private readonly IBranchBarrierFactory _barrierFactory;

        public TccBusinessController( IBranchBarrierFactory barrierFactory)
        {
            _barrierFactory = barrierFactory;
        }
        [HttpPost("TccBusinessTry")]
        public async Task<IActionResult> TccBusinessTry([FromQuery] string gid, [FromQuery] string trans_type,
            [FromQuery] string branch_id, [FromQuery] string op, [FromBody] OrderModel body)
        {


            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);
            DapperHelper dh = new DapperHelper();
            var obj= TransResponse.BuildSucceedResponse();
            using (MySqlConnection conn = new MySqlConnection(dh.connectstr()))
            {
                await branchBarrier.Call(conn, async (tx) =>
                {
                    var BusinessMoneys = dh.Query<BusinessMoney>($"select *  from Business_money where id={body.BusinessID} and balance=0");
                    if(BusinessMoneys.Count>0)
                    {
                        dh.Execute($"update Business_money set  balance=1,trading_balance=1 where id={body.BusinessID}");

                    }
                    else
                    {
                        obj= TransResponse.BuildFailureResponse();
                    }
                    await Task.CompletedTask;
                });
            }

            return Ok(obj);
        }

        [HttpPost("TccBusinessConfirm")]
        public async Task<IActionResult> TccBusinessConfirm([FromQuery] string gid, [FromQuery] string trans_type,
           [FromQuery] string branch_id, [FromQuery] string op, [FromBody] OrderModel body)
        {
        
            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);
            DapperHelper dh = new DapperHelper();
            var obj = TransResponse.BuildFailureResponse();
            using (MySqlConnection conn = new MySqlConnection(dh.connectstr()))
            {
                await branchBarrier.Call(conn, async (tx) =>
                {
                    var BusinessMoneys = dh.Query<BusinessMoney>($"select *  from Business_money where id={body.BusinessID}");
                    var money = BusinessMoneys[0].money + body.Money;
                    
                    dh.Execute($"insert into Business_Accounts values(null,{body.BusinessID},{body.UserId},{body.Money},'koukuan',{BusinessMoneys[0].money},'{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}')");
                    dh.Execute($"update Business_money set money={money},updatetime='{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}',balance=0,trading_balance=0 where id={body.BusinessID}");
                    obj = TransResponse.BuildSucceedResponse();
                    await Task.CompletedTask;
                });
            }

            return Ok(obj);
        }
        [HttpPost("TccBusinessCancel")]
        public async Task<IActionResult> TccBusinessCancel([FromQuery] string gid, [FromQuery] string trans_type,
           [FromQuery] string branch_id, [FromQuery] string op, [FromBody] OrderModel body)
        {
            
            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);

            DapperHelper dh = new DapperHelper();
            var obj = TransResponse.BuildFailureResponse();
            using (MySqlConnection conn = new MySqlConnection(dh.connectstr()))
            {
                await branchBarrier.Call(conn, async (tx) =>
                {
                    //这里操作回滚并解锁
                    var BusinessMoneys = dh.Query<BusinessMoney>($"select *  from Business_money where id={body.BusinessID}");
                    var money = BusinessMoneys[0].money - body.Money;
                    dh.Execute($"insert into Business_Accounts values(null,{body.BusinessID},{body.UserId},{body.Money},'koukuan',{BusinessMoneys[0].money},'{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}')");
                    dh.Execute($"update Business_money set money={money},updatetime='{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}',balance=0,trading_balance=0 where id={body.BusinessID}");
                    await Task.CompletedTask;
                });
            }

            return Ok(TransResponse.BuildSucceedResponse());
        }
    }
}
